package pannel.user;

import utils.JDBCUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    private static final String TABLE_NAME = "user";

    // 新增用户
    public boolean insert(User user) throws SQLException {
        String sql = "INSERT INTO " + TABLE_NAME + " (username, password, role, avatar_path) VALUES (?, ?, ?, ?)";
        int affected = (int) JDBCUtils.execute(sql,
                user.getUsername(),
                user.getPassword(),
                user.getRole(),
                user.getAvatarPath()
        );
        return affected > 0;
    }

    // 根据ID更新用户
    public boolean updateById(User user) throws SQLException {
        String sql = "UPDATE " + TABLE_NAME + " SET username = ?, password = ?, role = ?, avatar_path = ? WHERE id = ?";
        int affected = (int) JDBCUtils.execute(sql,
                user.getUsername(),
                user.getPassword(),
                user.getRole(),
                user.getAvatarPath(),
                user.getId()
        );
        return affected > 0;
    }

    // 根据ID删除用户
    public boolean deleteById(Integer id) throws SQLException {
        String sql = "DELETE FROM " + TABLE_NAME + " WHERE id = ?";
        int affected = (int) JDBCUtils.execute(sql, id);
        return affected > 0;
    }

    // 分页模糊查询
    public List<User> pageQuery(String username, Integer pageNum, Integer pageSize) throws SQLException {
        String sql = "SELECT * FROM " + TABLE_NAME + " WHERE username LIKE ? LIMIT ?, ?";
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql,
                "%" + (username != null ? username : "") + "%",
                (pageNum - 1) * pageSize,
                pageSize
        );

        List<User> users = new ArrayList<>();
        while (rs.next()) {
            users.add(mapResultSetToUser(rs));
        }
        return users;
    }

    // 获取总记录数
    public int getTotalCount(String username) throws SQLException {
        String sql = "SELECT COUNT(*) as total FROM " + TABLE_NAME + " WHERE username LIKE ?";
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql,
                "%" + (username != null ? username : "") + "%"
        );
        return rs.next() ? rs.getInt("total") : 0;
    }

    // 用户登录
    public User login(String username, String password) throws SQLException {
        String sql = "SELECT * FROM " + TABLE_NAME + " WHERE username = ? AND password = ?";
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql, username, password);
        return rs.next() ? mapResultSetToUser(rs) : null;
    }

    // 用户注册
    public boolean register(User user) throws SQLException {
        return !checkUsernameExists(user.getUsername()) && insert(user);
    }

    // 检查用户名是否存在
    public boolean checkUsernameExists(String username) throws SQLException {
        String sql = "SELECT COUNT(*) as count FROM " + TABLE_NAME + " WHERE username = ?";
        ResultSet rs = (ResultSet) JDBCUtils.execute(sql, username);
        return rs.next() && rs.getInt("count") > 0;
    }
    /**
     * 修改密码
     * @param id 用户ID
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return true:修改成功 false:修改失败
     * @throws SQLException SQL异常
     */
    public boolean updatePassword(Integer id, String oldPassword, String newPassword) throws SQLException {
        // 先验证旧密码是否正确
        String checkSql = "SELECT COUNT(*) as count FROM " + TABLE_NAME + " WHERE id = ? AND password = ?";
        ResultSet rs = (ResultSet) JDBCUtils.execute(checkSql, id, oldPassword);
        if (!rs.next() || rs.getInt("count") == 0) {
            return false;  // 旧密码验证失败
        }

        // 更新新密码
        String updateSql = "UPDATE " + TABLE_NAME + " SET password = ? WHERE id = ?";
        int affected = (int) JDBCUtils.execute(updateSql, newPassword, id);
        return affected > 0;
    }


    // ResultSet 映射到 User 对象
    private User mapResultSetToUser(ResultSet rs) throws SQLException {
        return User.builder()
                .id(rs.getInt("id"))
                .username(rs.getString("username"))
                .password(rs.getString("password"))
                .role(rs.getString("role"))
                .avatarPath(rs.getString("avatar_path"))
                .build();
    }
}